/**
 * Created by hsia on 2017/11/2.
 */
var isDao=true;
var btnInfo='';
var CenterPayment = function (targetObj) {
    this.targetObj = targetObj;
    this.sysUtils = new kendoUtils();
    this.init();
    return this;
}

CenterPayment.prototype = {
    init: function () {
        var bindFieldArray = this.sysUtils.getBindFieldArray(this.targetObj);
        var bindFunctionArray = [
            {fName: 'search_btn', fs: this.findGridData},
            {fName: 'reset_btn', fs: this.resetInfo}
        ];
        this.bindBaseModels = new bindBaseModel(null, bindFieldArray, bindFunctionArray, null);
        this.sysUtils.bindDoucment(this.bindBaseModels, this.targetObj, this);
        this.initOrz();
        this.findGridData();
    },
    initOrz: function () {
        var that = this;
        // 加载组织结构
        JsonpAjax(baseApiPath + 'recordMarket/ztreeData?gpcLev=chn', '', 'json', function (res) {
            var setting = {
                view: {
                    showLine: true,
                    selectedMulti: false,
                    dblClickExpand: false,
                    showIcon: false
                },
                data: {
                    key: {
                        name: "organizationName"
                    },
                    simpleData: {
                        enable: true,
                        idKey: "organizationCode",
                        pIdKey: "parentCode",
                        rootPId: ""
                    }
                }

            };
            var organizationTree = that.targetObj.find('#organization-tree4').lonixFloat({
                source: res,
                setting: setting,
                searchField: 'organizationName',
                target: that.targetObj.find('#organization_text4'),
                primary: function (nodes) {
                    if (isEmpty(nodes)) {
                        return;
                    }
                    that.sysUtils.mvvmModel.set('orgName', nodes[0].organizationName);
                    that.sysUtils.mvvmModel.set('orgGpc', nodes[0].organizationTypeCode);
                    that.sysUtils.mvvmModel.set('orgCode', nodes[0].organizationCode);
                    that.targetObj.find('#organization-tree4').fadeUp();
                },
                cancel: function (nodes) {
                    if (isEmpty(nodes)) {
                        return;
                    }
                    that.sysUtils.mvvmModel.set('orgName', '');
                    that.sysUtils.mvvmModel.set('orgGpc', '');
                    that.sysUtils.mvvmModel.set('orgCode', '');
                    that.targetObj.find('#organization-tree4').fadeUp();
                }
            });
        }, true);
    },
    findGridData: function (e) {
        var that = this;
        if (isNotEmpt(e)) {
            that = $(e.target).data("that");
        }
        if (validityForm(that.targetObj)) {
            var param = that.sysUtils.getBindDocJson(that.bindBaseModels.bindFieldArray);
            //转换时间格式
            if (isNotEmpt(param["beginTime"])) {
                param["beginTime"] = kendo.toString(param["beginTime"], 'yyyy-MM-dd HH:mm:ss');
            }
            if (isNotEmpt(param["endTime"])) {
                param["endTime"] = kendo.toString(param["endTime"], 'yyyy-MM-dd HH:mm:ss');
            }
            var dataT = {curdatetime: new Date().getTime(), jsonParam: JSON.stringify(param)};
            var source = that.sysUtils.getDataSource({
                url: baseApiPath + 'centralPayment/list',
                data: dataT,
                dataType: 'odata',
                pageSize: 12,
                requestEnd: that.requestEnd
            });
            that.targetObj.find("#pager").kendoPager({
                dataSource: source
            });
            that.targetObj.find("#listView").kendoListView({
                dataSource: source,
                selectable: "single",
                change:imgOverShow,
                template: kendo.template(that.targetObj.find("#template").html())
            });
            function imgOverShow() {
                var item = this.dataItem(this.select());
                if(item!=undefined){
                    var path = imgServerUrl+"/"+item.imgUrl;
                    //var path = 'https://ss1.bdstatic.com/70cFuXSh_Q1YnxGkpoWK1HF6hhy/it/u=4090279281,3257273322&fm=27&gp=0.jpg';
                    layer.closeAll('iframe');
                    // 记录当前时间戳
                    var start_time = new Date().getTime();
                    var theImage = new Image();
                    //theImage.src = path+'?'+start_time;
                    theImage.src = path;
                    // Get accurate measurements from that.
                    var imageWidth = theImage.width;
                    var imageHeight = theImage.height;

                    var check = function(){
                        // 只要任何一方大于0
                        // 表示已经服务器已经返回宽高
                        if(theImage.width>0 || theImage.height>0){
                            layer.open({
                                type: 2,
                                title: false,
                                shade: 0.1,
                                area: [theImage.width+'px', theImage.height+'px'],
                                skin: 'layui-layer-rim', //加上边框
                                closeBtn: 0,
                                shadeClose: true,
                                //time: 3000,
                                content:[ theImage.src, 'no']
                            });
                            clearInterval(set);
                        }
                    };
                    var set = setInterval(check,40);
                }
            }
        }
    },
    /**
     * Fired when a remote service request is finished.
     * @param e
     */
    requestEnd: function (e) {
        var response = e.response;
        var result = response.d.results;
        var type = e.type;
        if (!isEmpty(result)) {
            for (var o=0,l=result.length;o<l;o++) {
                var isPay = result[o]['isPay'];
                //var residenceTime = result[o]['residenceTime'];
                //var residenceSecs = residenceTime == undefined ? 0 : result[o]['residenceTime'] * 60 * 1000;
                var end = new Date(result[o].now).getTime();
                if (isPay == 1) {//超时时长
                    var start = new Date(result[o]['freeTime']).getTime() ;//+ residenceSecs;
                    var diff = end - start;
                    if (diff > 0) {
                        result[o]['timeOut'] = GetDateTimeDiff(start, end);
                    }else{
                        result[o]['timeOut'] = '';
                    }
                }

                var stop = GetDateTimeDiff(new Date(result[o]['inTime']).getTime(), end);
                result[o]['stop'] = stop;
                result[o]['stopTimeDay'] = stop.split(' ')[0];
                result[o]['stopTime'] = stop.substr(stop.indexOf(' ')+1,stop.length);
                result[o]['inTime'] = result[o]['inTime'].substr(0, 16);
            }
        }
        function GetDateTimeDiff(startMillisecond, endMillisecond) {
            var date = endMillisecond - startMillisecond;   //时间差的毫秒数

            //计算出相差天数
            var days = Math.floor(date / (24 * 3600 * 1000))

            //计算出小时数

            var leave1 = date % (24 * 3600 * 1000);    //计算天数后剩余的毫秒数
            var hours = Math.floor(leave1 / (3600 * 1000));
            //计算相差分钟数
            var leave2 = leave1 % (3600 * 1000);     //计算小时数后剩余的毫秒数
            var minutes = Math.floor(leave2 / (60 * 1000));
            //计算相差秒数
            var leave3 = leave2 % (60 * 1000);  //计算分钟数后剩余的毫秒数
            var seconds = Math.round(leave3 / 1000);
            return days + "天 " + hours + "小时 " + minutes + "分钟 " + seconds + "秒";
        }
    },
    openCenterChargePage: function (id, isPay) {
        var that = this;
        that.editResult = null;
        var openWindow = function () {
            that.editCenterCharge = that.sysUtils.openWindow(that.editCenterCharge, {
                title: '中央缴费',
                height: "600px",
                width: "830px",
                resizable: false,
                content: "/views/parkLotCenter/managerCenter/centralPayment_edit.html"
            }, true);
        };
        var ajaxPost = function () {
            JsonpAjax(baseApiPath + "centralPayment/queryOrder?recodeId=" + id+"&isPay="+isPay, null, "json", function (result) {
                that.editResult = result;
                openWindow();
            });
        };
        ajaxPost();
    },
    /*
     * 重置按钮
     */
    resetInfo: function (e) {
        var that = $(e.target).data("that");
        that.sysUtils.setBindFieldNull(that.bindBaseModels.bindFieldArray);
    }
}
var PayMentEdit = function (targetObj) {
    this.targetObj = targetObj;
    this.sysUtils = new kendoUtils();
    this.init();
    return this;
}
PayMentEdit.prototype = {
    init: function () {
        var fieldArray = this.sysUtils.getBindFieldArray(this.targetObj);
        var functionArray = [
            {fName: 'chargePay', fs: this.chargePay},
            {fName: 'checkCharge', fs: this.checkCharge}
        ];
        this.models = new bindBaseModel(null, fieldArray, functionArray, null);
        this.sysUtils.bindDoucment(this.models, this.targetObj, this);
        Utils.createDataDictDropDownList({
            div: this.targetObj.find('#vehicleType'),
            parentModelKey: BASIS.VEHICLE_TYPE.ROOT,
            select:Utils.getModelValueByModelKey(BASIS.VEHICLE_TYPE.COMPACT),
            change:this.DictDropDownListOnChange,
            unshift:true
        }, this);
        this.loadInfo();
    },
    DictDropDownListOnChange:function () {
        var item = this.dataItem(this.select());
        payMentEdit.checkCharge(item.modelValue);
        var editResult = centerPayment.editResult;
        editResult.vehicleType = item.modelValue;
    },
    loadInfo: function () {
        var that = this;
        var editResult = centerPayment.editResult;
        var tbody = that.targetObj.find("#orderTable > tbody");
        if (!isEmpty(editResult)) {
            that.showDaojs();

            if(editResult.svcName!=undefined){
                that.targetObj.find('#svcName').text(editResult.svcName);
                that.targetObj.find('#svcMoney').text(editResult.svcMoney);
                that.targetObj.find('#svcInfo').show();
            }
            that.sysUtils.mvvmModel.set('vehicleType',editResult.orders[0].vehicleType);
            editResult.vehicleType = editResult.orders[0].vehicleType;
            that.targetObj.find('#checkBtn').hide();
            that.checkCharge();


            if(editResult.isPay=='1'){
                that.targetObj.find('#csbj').text("出场超时费用：");
                btnInfo='立即补缴';
            }else{
                btnInfo='立即结算';
            }


            var map = {}, dest = [];
            var orders = editResult.orders;
            var l = orders.length;
            for (var i = 0; i < l; i++) {
                var obj = orders[i];

                if (!map[obj.orderCode]) {
                    dest.push({
                        orderCode: obj.orderCode,
                        parName: obj.parName,
                        //totalTime: GetDateTimeDiff(obj.totalTime*1000),
                        isPay: obj.isPay ==0 ? '未支付':'已支付',
                        isPayKey: obj.isPay,
                        dueMoney: obj.dueMoney == undefined ? 0 : obj.dueMoney,
                        chargeMoney: obj.chargeMoney == undefined ? 0 : obj.chargeMoney,
                        perMoney: obj.perMoney == undefined ? 0 : obj.perMoney,
                        inTime: obj.inTime == undefined ? 0 : obj.inTime,
                        hasSon: obj.hasSon,
                        data: obj.hasSon=='1'?[obj]:null
                    });
                    if(obj.hasSon=='1'){
                        map[obj.orderCode] = obj;
                    }
                } else {
                    for (var j = 0; j < dest.length; j++) {
                        var dj = dest[j];
                        if (dj.orderCode == obj.orderCode) {
                            dj.data.push(obj);
                            break;
                        }
                    }
                }
            }
            var chargeMoney =0,dueMoney=0,perMoney=0,areadyCharge=0;

            for(var o=0,l=dest.length;o<l;o++){
                var order = dest[o];
                var subTotal = 0;
                if(order.hasSon=='1'){
                    var subTr = $("<tr name='subTr' style='display: none'></tr>");
                    var td = $("<td colspan='6'></td>");
                    var subTable = $("<table class='table02'></table>");
                    var subThead = $("<thead></thead>");
                    var subTitle = $("<tr></tr>");
                    subTitle.append($("<td>所属分区</td>"));
                    subTitle.append($("<td>入场通道</td>"));
                    subTitle.append($("<td>计费开始时间</td>"));
                    subTitle.append($("<td>出场通道</td>"));
                    subTitle.append($("<td>计费结束时间</td>"));
                    subTitle.append($("<td>停留时间</td>"));
                    subThead.append(subTitle);
                    subTable.append(subThead);
                    var subTbody=$("<tbody></tbody>");

                    for(var d=0,s=order.data.length;d<s;d++){
                        var detail = order.data[d];
                        var out = false;
                        var dTr=$("<tr></tr>");
                        var start = new Date(detail.subInTime).getTime();
                        var end=0;
                        if(detail.subOutTime!=undefined){
                            out=true;
                            end = new Date(detail.subOutTime).getTime();
                        }else{
                            end = new Date(editResult.now).getTime();
                        }
                        subTotal+=end-start;
                        dTr.append($("<td>"+detail.subParName+"</td>"));
                        dTr.append($("<td>"+detail.subInchnName+"</td>"));
                        dTr.append($("<td>"+detail.subInTime+"</td>"));
                        dTr.append($("<td>"+(detail.subOutchnName==undefined?'-':detail.subOutchnName)+"</td>"));
                        dTr.append($("<td>"+(out?'-':detail.subOutTime)+"</td>"));
                        dTr.append($("<td>"+GetDateTimeDiff(end-start)+"</td>"));
                        subTbody.append(dTr);
                    }
                    subTable.append(subTbody);
                    td.append(subTable);
                    subTr.append(td);
                    tbody.append(subTr);
                }else{
                    var start = new Date(order.inTime).getTime(),end = new Date(editResult.now).getTime();
                    subTotal=end-start;
                }
                var tr=$("<tr></tr>");
                tr.append($("<td onclick='payMentEdit.changeSJ(this)'><img src='images/icon-hide.png'></td>"));
                tr.append($("<td>"+(o+1)+"</td>"));
                tr.append($("<td>"+order.parName+"</td>"));
                tr.append($("<td>"+GetDateTimeDiff(subTotal)+"</td>"));
                tr.append($("<td>"+order.isPay+"</td>"));
                if(order.isPayKey=='1'){
                    areadyCharge+=order.chargeMoney;
                }
                chargeMoney+=order.chargeMoney;
                dueMoney+=order.dueMoney;
                perMoney+=order.perMoney;
                tbody.prepend(tr);
            }
            that.targetObj.find('#areadyCharge').text("￥"+areadyCharge);
        }else{
            tbody.append($("<tr><td colspan='6' style='text-align:center;'>未查询到数据</td></tr>"));
            that.timeOut(null,'无支付订单');//无任何订单信息
        }
        if(!isEmpty(editResult)&&!isEmpty(editResult.imgs)){
            var imgs = editResult.imgs;
            var picDiv = that.targetObj.find(".pay-pic");
            for(var o in imgs){
                var img = imgs[o];
                var chnType = img.imgType=='I'?'进 ':'出 ';
                var div=$('<div class="picList" ></div>');
                div.append($('<div class="picInfo"><p>'+chnType+img.chnName+'</p><p>'+img.createTime+'</p></div>'));
                div.append($('<img width="100%" height="100%" src="'+imgServerUrl+'/'+img.imgUrl+'">'));
                picDiv.append(div);
            }
        }else{
            that.targetObj.find('.pay-pic').append("<span style='height:260px;line-height:260px;display:inline-block;font-size: xx-large;color: #96b2cb;align-content: center'>无图片信息</span>");
        }
        function GetDateTimeDiff(date) {
            //计算出相差天数
            var days = Math.floor(date / (24 * 3600 * 1000))

            //计算出小时数

            var leave1 = date % (24 * 3600 * 1000);    //计算天数后剩余的毫秒数
            var hours = Math.floor(leave1 / (3600 * 1000));
            //计算相差分钟数
            var leave2 = leave1 % (3600 * 1000);     //计算小时数后剩余的毫秒数
            var minutes = Math.floor(leave2 / (60 * 1000));
            //计算相差秒数
            var leave3 = leave2 % (60 * 1000);  //计算分钟数后剩余的毫秒数
            var seconds = Math.round(leave3 / 1000);
            return days + "天 " + hours + "小时 " + minutes + "分钟 " + seconds + "秒";
        }
        function GetDateTimeDiffBefore(startTime, endTime) {
            var retValue = {};

            var date = new Date(startTime).getTime() - new Date(endTime).getTime();  //时间差的毫秒数

            //计算出相差天数
            var days = Math.floor(date / (24 * 3600 * 1000));
            retValue.Days = days;

            var years = Math.floor(days / 365);
            retValue.Years = years;

            var months = Math.floor(days / 30);
            retValue.Months = months;

            //计算出小时数
            var leave1 = date % (24 * 3600 * 1000);    //计算天数后剩余的毫秒数
            var hours = Math.floor(leave1 / (3600 * 1000));
            retValue.Hours = hours;

            //计算相差分钟数
            var leave2 = leave1 % (3600 * 1000);        //计算小时数后剩余的毫秒数
            var minutes = Math.floor(leave2 / (60 * 1000));
            retValue.Minutes = minutes;

            //计算相差秒数
            var leave3 = leave2 % (60 * 1000);      //计算分钟数后剩余的毫秒数
            var seconds = Math.round(leave3 / 1000);
            retValue.Seconds = seconds;

            var strTime = "";
            if (years >= 1) {
                strTime = years + "年前";
            } else if (months >= 1) {
                strTime = months + "个月前";
            } else if (days >= 1) {
                strTime = days + "天前";
            } else if (hours >= 1) {
                strTime = hours + "小时前";
            } else {
                strTime = minutes + "分钟前";
            }
            retValue.PutTime = strTime;
            return retValue;
        }
    },
    changeSJ:function (obj) {
        var that = this;
        that.targetObj.find('tr[name="subTr"]').each(function () {
            $(this).hide();
        });
        var path = 'images/icon-show.png';
        var src = $(obj).find('img')[0].src;
        if(src.indexOf(path)>=0){
            $(obj).find('img')[0].src='images/icon-hide.png';
            $(obj).parent().next().hide();
        }else{
            $(obj).find('img')[0].src=path;
            $(obj).parent().next().show();
        }
    },
    chargePay:function () {
        var editResult = centerPayment.editResult;
        var obj = centerPayment.editResult;
        var pay = {};
        pay['recordId']=obj.recordId;
        pay['begtime']=obj.begtime;
        pay['vehicleType']=obj.vehicleType;
        pay['endtime']=obj.endtime;
        pay['payable']=obj.payable;

        pay['dueMoney']=obj.dueMoney;
        pay['preMoney']=obj.perMoney;
        pay['orderCode']=obj.orderCode;
        pay['orderNumber']=obj.orderNumber;
        pay['payMethod']=0;
        pay['carnumber']=obj.carnumber;
        pay['type']=0;
        pay['payPlatform']=3;
        if(editResult.isPay=='1'){
            pay['payType']=1;
        }else{
            pay['payType']=0;
        }
        JsonpAjax(baseApiPath+"centralPayment/orderPay",JSON.stringify(pay),"json",function(result){
            $("#"+centerPayment.editCenterCharge).data("kendoWindow").close();
            centerPayment.findGridData();
        });
    },
    showDaojs:function () {
        var that = this;
        isDao=true;
        var time = that.addMinutes(new Date(),2);
        that.targetObj.find('#daojs').fnTimeCountDown(time,that.timeOut,that);
    },
    addMinutes:function (date,minutes) {
        minutes=parseInt(minutes);
        var interTimes=minutes*60*1000;
        interTimes=parseInt(interTimes);
        return  new  Date(Date.parse(date)+interTimes);
    },
    timeOut:function (type,info,$that) {
        var that = this;
        if($that){
            that = $that;
        }
        if(isNotEmpt(type)&&type=='0'){
            isDao=false;
        }
        info = info!=undefined?info:'结算超时';
        that.targetObj.find('#checkBtn').show();
        that.targetObj.find('#chargeBtn').attr("disabled", true);
        that.targetObj.find('#chargeBtn').html(info);
        that.targetObj.find('#chargeBtn').css("background","#CCCCCC");
    },
    checkCharge:function (vehicleType) {
        var that = this;
        if(typeof vehicleType == 'object'){
            that=$(vehicleType.target).data("that");
        }
        var editResult = centerPayment.editResult;
        var id = editResult.orders[0].id;
        if(typeof vehicleType == 'object'|| vehicleType==undefined){
            vehicleType = editResult.orders[0].vehicleType;
        }
        that.targetObj.find('#chargeBtn').attr("disabled", true);
        //that.targetObj.find('#chargeBtn').html('获取缴费..');
        that.targetObj.find('#chargeBtn').css("background","#CCCCCC");
        JsonpAjax(baseApiPath + "centralPayment/checkCharge?recodeId=" + id+"&vehicleType="+vehicleType,null,"json",function(result){
            if(result.getPay){
                var obj = centerPayment.editResult;
                obj.recordId = result.recordId;
                obj.carnumber = result.carnumber;
                obj.endtime = result.endtime;
                obj.payable = result.payable;
                obj.dueMoney = result.dueMoney;
                obj.orderCode = result.orderCode;
                obj.preMoney = result.preMoney;
                obj.vehicleType = vehicleType;
                obj.orderNumber = result.orderNumber;

                if(result.payable>0){
                    if((result.svcMoney!=undefined&&parseFloat(result.payable) > parseFloat(result.svcMoney))||result.svcMoney==undefined ){
                        that.targetObj.find('#chargeBtn').removeAttr("disabled");
                        that.targetObj.find('#chargeBtn').html(btnInfo);
                        that.targetObj.find('#chargeBtn').css("background","#2590f1");
                        that.targetObj.find('#checkBtn').hide();
                    }
                    if((result.svcMoney!=undefined&&parseFloat(result.payable) > parseFloat(result.svcMoney)&&!isDao) || result.svcMoney==undefined&&!isDao){//储值卡自动缴费
                        that.showDaojs();
                    }
                }else{
                    obj.payable=0;
                    layer.tips('当前未产生费用,无需缴费...',that.targetObj.find('#chargeMoney'),{tipsMore: true,tips: [3, '#292929']});
                    that.targetObj.find('#chargeBtn').attr("disabled", true);
                    that.targetObj.find('#chargeBtn').css("background","#CCCCCC");
                }
                that.targetObj.find('#chargeMoney').text("￥"+obj.payable);
            }else{
                that.targetObj.find('#checkBtn').show();
                layer.tips('获取中央缴费失败，请联系管理员...',that.targetObj.find('#chargeMoney'),{tipsMore: true,tips: [3, '#292929']});
                that.timeOut(null,'获取费用失败');
            }
            that.targetObj.find('#svcMoney').html("￥"+result.svcMoney);
        });

    },
    sleep:function (n) {
        var start = new Date().getTime();
        while (true) if (new Date().getTime() - start > n) break;
    }
}